﻿namespace Rage.UI
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;
    using System.Windows.Media.Imaging;
    using System.Windows.Data;
    using System.ComponentModel;
    using System.Threading;
    using System.Windows.Threading;
    using Microsoft.Win32;

    public partial class DG_ToRLoader_AdvancedClass : ChildWindow
    {
        public DG_ToRLoader_AdvancedClass()
        {
            InitializeComponent();

            DG_ProgressBar = new UI.DG_ProgressBar();
            DG_ProgressBar.Closed += new EventHandler(DG_ProgressBar_Closed);

            BackgroundWorker _backgroundWorker = new BackgroundWorker();

            // Set up the Background Worker Events
            _backgroundWorker.DoWork += _backgroundWorker_DoWork;
            _backgroundWorker.RunWorkerCompleted += _backgroundWorker_RunWorkerCompleted;

            // Run the Background Worker
            _backgroundWorker.RunWorkerAsync(250);

            // Create the thread and kick it started!
            //new Thread(start).Start();
            DG_ProgressBar.Show();
        }

        DG_ProgressBar DG_ProgressBar;

        List<GomLib.Models.Item> items = new List<GomLib.Models.Item>();

        // Worker Method
        private void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            // Do something
            
            //TorLib.Assets.assetPath = new OpenFileDialog() { @"D:\Program Files\Electronic Arts\BioWare\Star Wars-The Old Republic\Assets";

            GomLib.DataObjectModel.Load();
            var itmList = GomLib.DataObjectModel.GetObjectsStartingWith("itm.").Where(obj => !obj.Name.StartsWith("itm.test.") && !obj.Name.StartsWith("itm.npc."));
            double i = 0;
            double cntSkipped = 0;
            double ttl = itmList.Count();
            Dispatcher.BeginInvoke((Action) delegate {
                DG_ProgressBar.UpdateProgress(i, ttl, cntSkipped/*, itm.Name*/);
                //DG_ProgressBar.AddLineToLog(itm.Name + " : Completed");
            });
            foreach (var gomItm in itmList)
            {
                GomLib.Models.Item itm = new GomLib.Models.Item();
                GomLib.ModelLoader.ItemLoader.Load(itm, gomItm);
                bool addIt = true;
                #region Filter by Invalid Item Type
                if (addIt)
                {
                    switch (itm.SubCategory)
                    {
                        case GomLib.Models.ItemSubCategory.Undefined:
                        case GomLib.Models.ItemSubCategory.OtherQuestItem:
                        case GomLib.Models.ItemSubCategory.OtherLockbox:
                        case GomLib.Models.ItemSubCategory.OtherCustomization:
                        case GomLib.Models.ItemSubCategory.OtherGift:
                        case GomLib.Models.ItemSubCategory.OtherCurrency:
                        case GomLib.Models.ItemSubCategory.OtherMount:
                        case GomLib.Models.ItemSubCategory.OtherPet:
                        case GomLib.Models.ItemSubCategory.CraftingMaterial:
                        case GomLib.Models.ItemSubCategory.CraftingSchematic:
                        case GomLib.Models.ItemSubCategory.ConsumableAdrenal:
                        case GomLib.Models.ItemSubCategory.ConsumableMedpac:
                        case GomLib.Models.ItemSubCategory.ConsumableStim:
                        case GomLib.Models.ItemSubCategory.ConsumableFood:
                        case GomLib.Models.ItemSubCategory.ConsumablePvp:
                        case GomLib.Models.ItemSubCategory.ConsumableGrenade:
                        case GomLib.Models.ItemSubCategory.EquipmentDroidPart:
                        case GomLib.Models.ItemSubCategory.OtherUnknown:
                        case GomLib.Models.ItemSubCategory.EquipmentSpace:
                            { addIt = false; break; }
                        default: { break; }
                    }
                }
                #endregion
                #region Filter by Low Quality
                if (addIt)
                {
                    switch (itm.Quality)
                    {
                        case GomLib.Models.ItemQuality.Cheap:
                        case GomLib.Models.ItemQuality.Standard:
                        //case GomLib.Models.ItemQuality.Premium:
                        //case GomLib.Models.ItemQuality.Prototype:
                        //case GomLib.Models.ItemQuality.Artifact:
                        //case GomLib.Models.ItemQuality.Legendary:
                        //case GomLib.Models.ItemQuality.Legacy:
                        case GomLib.Models.ItemQuality.Quest:
                        case GomLib.Models.ItemQuality.Currency:
                        //case GomLib.Models.ItemQuality.Moddable:
                            { addIt = false; break; }
                        default: {  break; }
                    }
                }
                #endregion
                #region Filter by Low Item Level
                if (addIt)
                {
                    if (itm.SubCategory == GomLib.Models.ItemSubCategory.ItemModColorCrystal) {
                        if (itm.ItemLevel < 40) { addIt = false; }
                    } else if (itm.SubCategory == GomLib.Models.ItemSubCategory.ItemModArmoring
                        || itm.SubCategory == GomLib.Models.ItemSubCategory.ItemModAugment
                        || itm.SubCategory == GomLib.Models.ItemSubCategory.ItemModMod
                        || itm.SubCategory == GomLib.Models.ItemSubCategory.ItemModEnhancement
                        || itm.SubCategory == GomLib.Models.ItemSubCategory.ItemModBarrel
                        || itm.SubCategory == GomLib.Models.ItemSubCategory.ItemModHilt
                        ) {
                        if (itm.ItemLevel < 45) { addIt = false; }
                    } else {
                        if (itm.ItemLevel < 48) { addIt = false; }
                    }
                }
                #endregion
                #region Filter by bad names
                if (addIt && string.IsNullOrEmpty(itm.Name)) { addIt = false; }
                if (addIt)
                {
                    List<String> badStartsWithValues = new List<String>()
                    {
                        "TBD",
                        "Andronikos Revel",
                        "Ashara",
                        "Blizz",
                        "Bowdaar",
                        "Broonmark",
                        "Corso",
                        "Doc",
                        "Elara",
                        "Gault",
                        "Guss Tuno",
                        "Iresso",
                        "Jaesa",
                        "Jorgan",
                        "Kaliyo",
                        "Khem Val",
                        "Kira",
                        "Lokin",
                        "Mako",
                        "Nadia",
                        "Pierce",
                        "Quinn",
                        "Qyzen",
                        "Risha",
                        "Rusk",
                        "Scourge",
                        "Skadge",
                        "Spar",
                        "Talos",
                        "Tanno",
                        "Temple",
                        "Tharan",
                        "Torian",
                        "Vector",
                        "Vette",
                        "Vik",
                        "Xalek",
                        "Yuun",
                        "Zenith",
                        "Zez-Kai Ell",
                    };
                    foreach(string s in badStartsWithValues) {
                        if (itm.Name.StartsWith(s)) { addIt = false; break; }
                    }
                }
                #endregion
                if (addIt) { items.Add(itm); } else { cntSkipped++; }
                Dispatcher.BeginInvoke((Action) delegate {
                    DG_ProgressBar.UpdateProgress(i, ttl, cntSkipped);
                });
                i++;
            }
            view = new ListCollectionView(items);
            //view.GroupDescriptions.Add(new PropertyGroupDescription("Category"));
            //view.GroupDescriptions.Add(new PropertyGroupDescription("SubCategory"));
            //view.GroupDescriptions.Add(new PropertyGroupDescription("ItemLevel"));
            //view.SortDescriptions.Add(new SortDescription("Id", ListSortDirection.Ascending));
            //view.SortDescriptions.Add(new SortDescription("SubCategory", ListSortDirection.Ascending));
        }
        ListCollectionView view;

        // Completed Method
        private void _backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled) {
                DG_ProgressBar.statusText.Text = "Cancelled";
            } else if (e.Error != null) {
                DG_ProgressBar.statusText.Text = "Exception Thrown";
            } else {
                DG_ProgressBar.statusText.Text = "Completed";
            }
            Dispatcher.BeginInvoke((Action)delegate
            {
                DG_ProgressBar.FinishProgress();
            });
            //DG_ProgressBar.BT_Cancel.IsEnabled = false;
            Dispatcher.BeginInvoke((Action)delegate
            {
                ItemGrid.ItemsSource = view;
            });
            
        }

        // Worker Method
        private void _backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            // Do something
            double i = 0;
            double cntSkipped = 0;
            double ttl = items.Count;
            Dispatcher.BeginInvoke((Action)delegate
            {
                DG_ProgressBar.UpdateProgress(i, ttl, cntSkipped);
            });
            foreach (var /*GomLib.Models.Item*/ dItem in view)
            {
                if (!(dItem is GomLib.Models.Item)) { cntSkipped++; continue; }
                try
                {
                    Item lItem = Item.FromToRItem(dItem as GomLib.Models.Item);
                    ItemCache.AddItem(lItem);
                }
                catch (Exception ex)
                {
                    errors[dItem] = ex;
                    cntSkipped++;
                }
                finally
                {
                    Dispatcher.BeginInvoke((Action)delegate
                    {
                        DG_ProgressBar.UpdateProgress(i, ttl, cntSkipped);
                    });
                    i++;
                }
            }
            if (errors.Keys.Count > 0)
            {
                string s = "";
                foreach (KeyValuePair<object, Exception> kvp in errors)
                {
                    s += string.Format("{0}: {1}\n", kvp.Key, kvp.Value.Message);
                }
                MessageBox.Show(s, "Errors Happened");
            }
        }
        // Completed Method
        private void _backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled) {
                DG_ProgressBar.statusText.Text = "Cancelled";
            } else if (e.Error != null) {
                DG_ProgressBar.statusText.Text = "Exception Thrown";
            } else {
                DG_ProgressBar.statusText.Text = "Completed";
            }
            Dispatcher.BeginInvoke((Action)delegate
            {
                DG_ProgressBar.FinishProgress();
            });
            //DG_ProgressBar.BT_Cancel.IsEnabled = false;
            Dispatcher.BeginInvoke((Action)delegate
            {
                //ItemGrid.ItemsSource = view;
            });
            
        }

        private void DG_ProgressBar_Closed(object sender, EventArgs e)
        {
            LB_Count.Text = DG_ProgressBar.TB_Perc.Text;
        }

        private void BT_ExtractImages_Click(object sender, RoutedEventArgs e)
        {
            TorLib.Icons.SaveTo(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), @"images\"), true);
            TorLib.Icons.ConvertDDSToJPG();
        }

        private Dictionary<object, Exception> errors = new Dictionary<object, Exception>();
        private void BT_Import_Click(object sender, RoutedEventArgs e)
        {
            DG_ProgressBar = new UI.DG_ProgressBar();
            DG_ProgressBar.Closed += new EventHandler(DG_ProgressBar_Closed);

            BackgroundWorker _backgroundWorker2 = new BackgroundWorker();

            // Set up the Background Worker Events
            _backgroundWorker2.DoWork += _backgroundWorker2_DoWork;
            _backgroundWorker2.RunWorkerCompleted += _backgroundWorker2_RunWorkerCompleted;

            // Run the Background Worker
            _backgroundWorker2.RunWorkerAsync(250);

            // Create the thread and kick it started!
            //new Thread(start).Start();
            DG_ProgressBar.Show();
        }

        private void OKButton_Click(object sender, RoutedEventArgs e) { this.DialogResult = true; }
    }
}

